package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.smbms.dao.user.UserMapperTest;
import cn.smbms.pojo.User;

/**
 * Servlet implementation class LoginServlet
 */

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public LoginServlet() {
		// TODO Auto-generated constructor stub
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		// request.setCharacterEncoding("utf-8");
		// response.setCharacterEncoding("utf-8");

		String userName = request.getParameter("username");
		String password = request.getParameter("password");

		UserMapperTest umt = new UserMapperTest();
		List<User> userList = umt.testGetUserList();

		for (User uu : userList) {

			if (userName.equals(uu.getUserCode())
					&& password.equals(uu.getUserPassword())) {
				request.setAttribute("user", uu);
				request.getRequestDispatcher("welcome.jsp").forward(request,
						response);
				return;
			}

		}// for
		PrintWriter out = response.getWriter();
		out.print("<script>alert('账号或密码错误');location='login.jsp';</script>");
		out.flush();

	}
}
